//业务待办和已办详情页
var app = getApp()
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    commonUrl: app.GLOBAL_CONFIG.commonUrl,
    businessTaskId:0,//具体任务的id
    businessTask:null,//业务实例

    taskDiscussList:null,//任务讨论列表
    taskDiscussUrl:[],

    instance:null,//任务讨论实例
    focus:false,//是否聚焦在输入框
    taskType:'',//一般任务或特定任务
    user:null,
    finishedTaskFlag:0,//是否完成（checkbox）
    textareaValue:'',//textarea输入框value，用于在提交完成后进行清空操作
    
    relaAttachmentUrl:[],//任务相关附件
    attachment:[],//后台返回的附件信息

    showModalStatus:false,//上传modal显示控制
    imgsArr:[],//讨论部分选中的图片
    imgIcon: true,//上传框图片是否超过九张，超过则不再显示索引icon

    resFileUrl:[],
    resFile:[],//图片上传成功后返回的resource表的id

    uploadFinish:true,//上传图片操作是否完成 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (obj) {
    var that = this;
    that.setData({
      businessTaskId: obj.businessTaskId,
      user: app.globalData 
    })
    if (utils.checkNetWorkStatus() == false) {
      console.log('网络错误');
      wx.navigateBack({
        delta: 1
      })
      wx.showToast({
        title: '网络错误请检查',
        duration: 2000,
      })
    } else {
      var url = app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.businessTaskDetail + "?id=" + that.data.businessTaskId,
        cookie = app.globalData.cookie;
      utils.getRequest(url, cookie, app,that, that.successOper, function (res) {
        wx.navigateBack({
          delta:1
        })
        wx.showToast({
          title: '获取数据失败，请稍后重试',
          image: '../../images/fail.png',
          duration: 2000
        })
      })
    }
  },

  successOper:function(res,that){
    if (res.data.success == true && res.data.taskType == "common") {//普通
      var taskList;
      if (res.data.taskDiscussList.length == 0) {
        taskList = null;
      } else {
        taskList = res.data.taskDiscussList
        var taskDiscussUrl =[] 
        for(let i=0;i<taskList.length;i++){
          let discussResour =taskList[i].resources
          if (discussResour != null) {
            taskDiscussUrl = taskDiscussUrl.concat(utils.getAttacheUrls(discussResour, app))
          }
        }
        that.setData({ taskDiscussUrl: taskDiscussUrl })
      }

      var attachment = res.data.attachment,
        attachUrls = utils.getAttacheUrls(attachment, app)
      that.setData({
        businessTask: res.data.businessTask,
        taskDiscussList: taskList,
        instance: res.data.instance,
        taskType: res.data.taskType,
        attachment: attachment,
        relaAttachmentUrl: attachUrls
      })
    } else if (res.data.success == true && res.data.taskType == "special") {//特定
      wx.showModal({
        title: '提示',
        content: '请前往PC端处理',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })

    } else {//失败
      wx.navigateBack({
        delta: 1
      })
      wx.showToast({
        title: '获取数据失败，请稍后重试',
        image: '../../images/fail.png',
        duration: 2000
      })

    }
  },

/**
 * 任务办理
 */
  descriptionSubmit:function(e){
    var that = this,
      attachmentIds = '',
      resFile = that.data.resFile,
      finishedTaskFlag = that.data.finishedTaskFlag,
      content = e.detail.value.content
    for (var i = 0; i < resFile.length; i++){
      attachmentIds = attachmentIds.concat(','+resFile[i].id)
    }  
    console.log("文本输入框内容 " + content)

    if (content == null || content == ''){
      wx.showToast({
        title: '请填写描述',
        image: '../../images/warning.png',
        duration: 2000
      })
      this.setData({
        focus: true
      })
    }else{
      if (utils.checkNetWorkStatus() == false) {
        console.log('网络错误');
        wx.showToast({
          title: '网络错误请检查',
          duration: 2000,
        })
      } else {
        var url = app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.businessTaskHandle + "?content=" + content + "&finishedTaskFlag=" + that.data.finishedTaskFlag + "&taskId=" + that.data.businessTask.id + "&attachmentIds=" + attachmentIds,
          cookie = app.globalData.cookie
        utils.postRequest(url, cookie,app, that, function(res,that){
          if (res.data.success == true) {
            console.log("success")
            var taskList
            if (res.data.taskDiscussList.length == 0) {
              taskList = null
            } else {
              taskList = res.data.taskDiscussList
              var taskDiscussUrl = []
              for (let i = 0; i < taskList.length; i++) {
                let discussResour = taskList[i].resources
                if (discussResour != null) {
                  taskDiscussUrl = taskDiscussUrl.concat(utils.getAttacheUrls(discussResour, app))
                }
              }
              that.setData({ taskDiscussUrl: taskDiscussUrl })
            }
            that.setData({
              taskDiscussList: taskList,
              businessTask: res.data.businessTask,
              textareaValue: '',
              resFile: [],

            })

          } else {
            wx.showToast({
              title: '操作失败，请稍后重试',
              image: '../../images/fail.png',
              duration: 2000
            })

          }
        }, function (res) {
          wx.showToast({
            title: '操作失败，请稍后重试',
            image: '../../images/fail.png',
            duration: 2000
          })
        })
      }
    }
  },



/**
 * 任务确认完成：暂不需要
 * @Deprecated
 */
  confirmSubmit:function(){
    var that = this;
    wx.request({
      url: app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.businessTaskConfirm + "?id=" + that.data.businessTask.id,
      header: app.globalData.header,
      method: "POST",
      success:function(res){
        if(res.data == "success"){
          that.setData({
            taskDiscussList: res.data.taskDiscussList,
            businessTask: res.data.businessTask
          })
        }else{
          wx.showToast({
            title: '获取数据失败，请稍后重试',
            image: '../../images/fail.png',
            duration: 2000
          })

        }
      }
    })

  },

  listenCheckboxChange:function(e){
    this.setData({
      finishedTaskFlag:e.detail.value
    })

  },



  chooseImageTap: function () {
    let that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })  

  },

  chooseWxImage: function (type) {
    var that = this;
    if (that.data.imgsArr.length<9){
      wx.chooseImage({
        sizeType: ['original', 'compressed'],
        sourceType: [type],
        success: function (res) {
          console.log(res);
          that.setData({
            imgsArr: that.data.imgsArr.concat(res.tempFilePaths)
          })
        }
      })
      if (that.data.imgsArr.length == 8){
        that.setData({ imgIcon: false })//超过九张则不再显示索引icon
      }

    }else{
      that.setData({ imgIcon: false })//超过九张则不再显示索引icon
      wx.showToast({
        title: '最多上传九张图片',
        image:'../../images/warning.png',
        duration: 3000
      });  

    }
  
  },

  bindUploadFile:function(){
    var that = this,
      url = app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.uploadFile,
      cookie = app.globalData.cookie
    if (that.data.imgsArr.length==0){
      wx.showToast({
        title: '请至少选择一张照片',
        image: '../../images/warning.png',
        duration: 1000
      });  
      return
    }
    var formData = {
      fileWidgetId: 'testImage',
      folder: 'miniprogram'
    }

    for (var i = 0; i < that.data.imgsArr.length;i++){
      utils.upload_file(url, cookie, that.data.imgsArr[i], 'photos', formData, function (res) {
        var returnValue = JSON.parse(res.data)
        that.setData({
          resFileUrl: that.data.resFileUrl.concat(app.GLOBAL_CONFIG.commonUrl + returnValue.resPath),
          resFile: that.data.resFile.concat(returnValue)
        })
      },
      function () {
          wx.showToast({
            title: '上传失败请重试',
            image:'../../images/fail.png',
            duration:2000
          })
        })
    }

    that.setData({ 
      showModalStatus: false,
      imgsArr:[],
      imgIcon:true
       })
    that.executeFun()
 
  },
  bindSaveTap: function (e) {
    var modalStatu = e.currentTarget.dataset.statu
    if (modalStatu == 'open') {
      this.setData({
        showModalStatus: true
      })
    }
  },

  //TODO 将基础信息附件及讨论详情分别加上id并通过id来区分二者，分别对的预览路径做整理，最后调用预览函数实现预览
  viewAttachment: function (e) {
    var that = this,
      fileType = e.target.dataset.type,
      id = e.target.id,
      basicSet = id.indexOf("basicFile"),
      discussSet = id.indexOf("discussFile"), 
      current = app.GLOBAL_CONFIG.commonUrl  + e.target.dataset.src,
      attachmentUrl = []
    if(basicSet >= 0 && discussSet ==-1){//任务基础附件
      attachmentUrl = that.data.relaAttachmentUrl
    } else if (basicSet == -1 && discussSet >= 0){//讨论内容附件
      attachmentUrl = that.data.taskDiscussUrl
    }
   
    fileType = fileType.toLocaleLowerCase()
    switch (fileType) {
      /**
       * 图片格式
       */
      case '.png':
        utils.imagePreview(current, attachmentUrl);
        break;
      case '.jpg':
        utils.imagePreview(current, attachmentUrl);
        break;
      case '.bmp':
        utils.imagePreview(current, attachmentUrl);
        break;
      case '.jpeg':
        utils.imagePreview(current, attachmentUrl);
        break;
      /**
       * 其他格式
       暂时屏蔽，若需要下载，再实现
       */
      case '.pdf':
        utils.documentOperate(current);
        break;
      case '.docx':
        utils.documentOperate(current);
        break;
      case '.doc':
        utils.documentOperate(current);
        break;
      case '.xlsx':
        utils.documentOperate(current);
        break;
      case '.xls':
        utils.documentOperate(current);
        break;
      case '.pptx':
        utils.documentOperate(current);
        break;
      case '.ppt':
        utils.documentOperate(current);
        break;
      default:
        wx.showToast({
          title: '不支持的文件类型',
          image: '../../images/warning.png'
        })
        break;
    }
  },




/**
 * 删除
 */
  deletePic:function(e){ 
    var index = e.currentTarget.dataset.index,
      id = e.target.id,
      offset = id.indexOf("unUpload"),
      unsendSet = id.indexOf("upUnSend"),
      currId = e.currentTarget.dataset.itemid
    if (offset == 0 && unsendSet == -1) {
      var imgs = this.data.imgsArr
      imgs.splice(index, 1)
      this.setData({
        imgsArr: imgs
      });
    }else{
      var resFile = this.data.resFile
      for (var i = resFile.length - 1; i >= 0; i--){
        if (resFile[i].id == currId){
          resFile.splice(i, 1)
          var resUrls = this.data.resFileUrl
          resUrls.splice(index,1)
          this.setData({
            resFile:resFile,
            resFileUrl:resUrls
          })
        }
         

      }
      

    }
   
  },
  /**
   * 选择预览或删除
   */
  chooseActionSheet: function (e) {
    var that = this
    wx.showActionSheet({
      itemList: ['预览','删除'],
      itemColor: "#f7982a",
      success:function(res){
        if (res.tapIndex == 0) {//预览
          var index = e.currentTarget.dataset.index,
            id = e.target.id,
            offset = id.indexOf("unUpload"),
            unsendSet = id.indexOf("upUnSend")
          if (offset >= 0 && unsendSet == -1){//还未上传的附件预览
            var imgs = that.data.imgsArr
            utils.imagePreview(imgs[index], imgs)
          } else {//已上传，但还未确定回复时
            var current = app.GLOBAL_CONFIG.commonUrl + e.currentTarget.dataset.src
            utils.imagePreview(current, that.data.resFileUrl)

          }
        } else if (res.tapIndex == 1) {//删除
          that.deletePic(e)
        }
      },
      fail:function(res){
        wx.showToast({
          title: res.errMsg,
          image:'../../images.fail.png'
        })
      }
    })
  },

  closeModal:function(e){
    var modalStatu = e.currentTarget.dataset.statu
    if(modalStatu == 'close'){
      this.setData({ 
        showModalStatus:false,
        imgsArr: []
        })
      this.executeFun()
    }
  },

  //  动画部分
  executeFun: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.opacity(0).rotateX(-100).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step()
      this.setData({
        // animationData: animation.export()
        animationData: ''//该bug真乃伟大举动哪！给自己点个赞
      })
    }.bind(this), 200) 
    
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})